package com.czk.netty.netty.tcp.server;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.nio.charset.Charset;
import java.util.UUID;

/**
 * @Author:ChenZhangKun
 * @Date: 2021/1/24 16:06
 */
public class MyServerHandler extends SimpleChannelInboundHandler<ByteBuf> {
    private int count;

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf) throws Exception {
        byte[] bytes = new byte[byteBuf.readableBytes()];
        byteBuf.readBytes(bytes);
        // 转成字符串
        String message = new String(bytes, Charset.forName("UTF-8"));
        // 接收的消息
        System.out.println("服务器接收消息message=" + message);
        // 服务器接收的消息量是 测试服务器接收消息接受了多少次
        System.out.println("服务器接收的消息量是" + (++this.count));
        // 回复数据给客户端
        channelHandlerContext.writeAndFlush(Unpooled.copiedBuffer(UUID.randomUUID().toString(),Charset.forName("utf-8")));
    }
}
